package com.wan.activity;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.wan.activity.util.EditTextFocusLintener;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.HttpUtils;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.WanServerResposeCode;

import java.util.HashMap;
import java.util.regex.Pattern;

import net.sourceforge.simcpux.Util;

//------------------------------------------------------------------------
// 忘记密码
//
//
//------------------------------------------------------------------------
public class forgetPasswordActivity extends BaseActivity implements
		View.OnClickListener {
	public static Activity activity = null;
	private final int REGESTER_SUCCESS = WanServerResposeCode.WAN_REGESTER_SUCCESS;
	private final int BIND_SUCCESS = WanServerResposeCode.WAN_REGESTER_FAILURE;
	private final int CHANGE_SUCCESS = 3;
	private final int BIND_FAIL = 4;
	private final int NETWORK_ERROR = 10086;
	private TimeCount time;
	private Button btn_getcode, btn_getpassword, btn_changepassword;
	private TextView forget_back_btn;
	private EditText username, mobileNumber, checkCode, password, re_password;
	private TextView forget_hint;
	private String _username, _phoneNumber, _code, _userid, _password, status;
	private Thread mThread;
	private int type;
	private Button forget_un_edclose,forget_check_edclose;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (WanCommonSdk.screen_orientation == WanCommonSdk.SCREEN_ORIENTATION_PORTRAIT) {
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("forgetpassword", "layout"));
		
		activity = this;
		time = new TimeCount(60000, 1000);
		this.btn_getcode = (Button) findViewById(Util.getResID("btn_getcode", "id"));
		
		btn_getcode.setOnClickListener(this);
		forget_back_btn = (TextView) findViewById(Util.getResID("forget_back_btn", "id"));
		 
		forget_back_btn.setOnClickListener(this);
		this.btn_getpassword = (Button) findViewById(Util.getResID("btn_getpassword", "id"));
		
		btn_getpassword.setOnClickListener(this);
		this.btn_changepassword = (Button) findViewById(Util.getResID("btn_changepassword", "id"));
		
		btn_changepassword.setOnClickListener(this);
		this.username = (EditText) findViewById(Util.getResID("username", "id"));
		
		this.mobileNumber = (EditText) findViewById(Util.getResID("mobileNumber", "id"));
		
		this.checkCode = (EditText) findViewById(Util.getResID("checkCode", "id"));
		
		this.password = (EditText) findViewById(Util.getResID("password", "id"));
		
		this.re_password = (EditText) findViewById(Util.getResID("re_password", "id"));
		
		this.forget_hint = (TextView) findViewById(Util.getResID("forget_hint", "id"));
		forget_un_edclose = (Button) findViewById(Util.getResID("forget_un_edclose", "id"));
		
		forget_check_edclose = (Button) findViewById(Util.getResID("forget_check_edclose", "id"));
		
		username.setOnFocusChangeListener(new EditTextFocusLintener(username, forget_un_edclose));
		checkCode.setOnFocusChangeListener(new EditTextFocusLintener(checkCode, forget_check_edclose));
		
	}

	// ------------------------------------------------------------------------
	//
	// 消息处理
	//
	// ------------------------------------------------------------------------
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REGESTER_SUCCESS:
				hideLoading();
				Toast.makeText(getApplicationContext(), "收到验证码后请填写",
						Toast.LENGTH_SHORT).show();
				
				break;
			case BIND_SUCCESS:
				hideLoading();
				findViewById(Util.getResID("LinearLayout1", "id")).setVisibility(View.GONE);
				forget_hint.setText(Util.getResID("check_password_hint", "string"));
				
				findViewById(Util.getResID("LinearLayout2", "id")).setVisibility(View.VISIBLE);

				break;
			case CHANGE_SUCCESS:
				forget_hint.setText(Util.getResID("change_password_hint", "string"));
				

				findViewById(Util.getResID("LinearLayout2", "id")).setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(), "密码修改成功",
						Toast.LENGTH_SHORT).show();
				finish();
				break;
			case NETWORK_ERROR:
				hideLoading();
				mThread = null;
				Toast.makeText(getApplicationContext(), "网络出现问题，请重试",
						Toast.LENGTH_SHORT).show();
				break;
			case 706:
				hideLoading();
				time.cancel();
				time.onFinish();
//				time.start();
				Toast.makeText(getApplicationContext(), "去用户中心绑定手机",
						Toast.LENGTH_SHORT).show();
				break;
			case 705:
				time.cancel();
				time.onFinish();
				hideLoading();
				Toast.makeText(getApplicationContext(), "输入手机号与已绑定手机号不一致",
						Toast.LENGTH_SHORT).show();
				break;
			case BIND_FAIL:
				hideLoading();
				Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();
				break;
			default:
				hideLoading();
				showToast(status);
				mThread = null;
				break;
				
			}
		}
	};

	// ------------------------------------------------------------------------
	//
	// 线程处理
	//
	// ------------------------------------------------------------------------
	Runnable runnable = new Runnable() {
		@Override
		public void run() {

			if (type == 1) {
				HashMap<String, String> result = HttpUtils.HttpSendCode(
						_userid, "bind", _phoneNumber);
				Util.LogUtil("forgetPassword---1---result:" + result);
				if (result == null) {
					mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
					return;
				}else if (result.get("status").equals(
						String.valueOf(REGESTER_SUCCESS))) {

					Conet.mUserInfo.setUser_id(result.get("user_id"));
					Conet.mUserInfo.setAccess_token(result.get("access_token"));
					mHandler.obtainMessage(REGESTER_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
					return;
				} else {
					// commend = result.get("commend");
				}
				mHandler.obtainMessage(Integer.parseInt(result.get("status")))
						.sendToTarget();
			} else if (type == 2) {
				HashMap<String, String> result = HttpUtils.HttpBindMobile(
						_userid, "check", _code, _phoneNumber);
				Util.LogUtil("forgetPassword---2---result:" + result);
				if (result == null) {
					mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
					return;
				}
				if (result.get("status").equals(
						String.valueOf(REGESTER_SUCCESS))) {
					// UserInfo userInfo = new UserInfo();
					Conet.mUserInfo.setUser_id(result.get("user_id"));
					Conet.mUserInfo.setAccess_token(result.get("access_token"));
					mHandler.obtainMessage(BIND_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
					return;
				}
				mHandler.obtainMessage(Integer.parseInt(result.get("status")))
						.sendToTarget();
			} else if (type == 3) {

				HashMap<String, String> result = HttpUtils
						.HttpUpdatePasswrd(_username, _password, _code,
								_userid, "2", _phoneNumber);
				Util.LogUtil("forgetPassword---3---result:" + result);
				if (result == null) {
					mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
					return;
				}
				if (result.get("status").equals(
						String.valueOf(REGESTER_SUCCESS))) {
					// UserInfo userInfo = new UserInfo();
					Conet.mUserInfo.setUser_id(result.get("user_id"));
					Conet.mUserInfo.setAccess_token(result.get("access_token"));
					mHandler.obtainMessage(CHANGE_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
					return;
				}
				status = result.get("status").toString();
				mHandler.obtainMessage(Integer.parseInt(result.get("status")))
						.sendToTarget();
			}
		}
	};

	// ------------------------------------------------------------------------
	//
	// 事件处理
	//
	// ------------------------------------------------------------------------
	@Override
	public void onClick(View v) {

		if (v.getId() == Util.getResID("forget_back_btn", "id")) {
			
			finish();
		} else if (v.getId() == Util.getResID("btn_getcode", "id")) {
			
			if (checkPhone()) {
				sendcode();

			}
		} else if (v.getId() == Util.getResID("btn_getpassword", "id")) {
			
			if (checkPhone() && checkCode()) {
				findpassword();
			}
		} else if (v.getId() == Util.getResID("btn_changepassword", "id")) {
			
			if (checkPassword()) {
				_password = this.password.getText().toString();
				changePassword();
			}
		}
	}

	private Boolean checkPhone() {
		int un_length = this.mobileNumber.getText().toString().length();

		Pattern pattern = Pattern.compile("[0-9]*");
		Boolean num = pattern.matcher(this.mobileNumber.getText().toString())
				.matches();
		if (un_length == 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("mobile_phone", "string")), Toast.LENGTH_SHORT)
					.show();
			
			return false;
		}
		if (un_length != 11 && num) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("mobile_phone_wrong", "string")),
					
					Toast.LENGTH_SHORT).show();
			return false;
		}

		return true;
	}

	private void sendcode() {
		time.start();
		_username = this.username.getText().toString();

		if (_username.length() <= 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("username_empty_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return;
		}
		final Handler sendHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				HashMap<String, String> result = (HashMap<String, String>) msg.obj;
				_userid = result.get("user_id").toString();
				Conet.mUserInfo.setUser_id(_userid);
				Conet.mUserInfo.setUser_name(_username);
				_phoneNumber = mobileNumber.getText().toString();
				showLoading(getString(Util.getResID("log_sendcode_hint", "string")));
				
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						HashMap<String, String> result = HttpUtils
								.HttpSendCode(_userid, "check", _phoneNumber);
						if (result == null) {
							mHandler.obtainMessage(NETWORK_ERROR)
									.sendToTarget();
							return;
						} else if (result.get("status").equals(
								String.valueOf(REGESTER_SUCCESS))) {
							Conet.mUserInfo.setBind_Phone(_phoneNumber);
							mHandler.obtainMessage(REGESTER_SUCCESS,
									Conet.mUserInfo).sendToTarget();
							return;
						}else if(result.get("status").equals("705")){
							Message msg = mHandler.obtainMessage();
							msg.what = 705;
							mHandler.sendMessage(msg);
							
						}else if(result.get("status").equals("706")){
							Message msg = mHandler.obtainMessage();
							msg.what = 706;
							mHandler.sendMessage(msg);
						}
					}
				}).start();
			}
		};
		new Thread(new Runnable() {

			@Override
			public void run() {
				HashMap<String, String> result = HttpUtils
						.HttpGetUserid(_username);
				if (Integer.valueOf(result.get("status").toString()) == 0
						&& result.get("user_id").toString().length() > 0) {
					Message msg = sendHandler.obtainMessage();
					msg.obj = result;
					sendHandler.sendMessage(msg);

				}

			}
		}).start();
	}

	private void findpassword() {
		_code = checkCode.getText().toString();
		showLoading();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HashMap<String, String> result = HttpUtils.HttpBindMobile(
						_userid, "check", _code, _phoneNumber);

				if (result == null) {
					mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
					return;
				} else {
					if (result.get("status").equals(
							String.valueOf(REGESTER_SUCCESS))) {
						String ss = result.toString();
						mHandler.obtainMessage(BIND_SUCCESS, Conet.mUserInfo)
								.sendToTarget();
					} else {
						mHandler.obtainMessage(BIND_FAIL, Conet.mUserInfo)
						.sendToTarget();
					}
				}
			}
		}).start();
	}

	private void checkUser(final int what) {
		
		final Handler checkhandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				HashMap<String, String> result = (HashMap<String, String>) msg.obj;
				if (what == 1) {
					if (Integer.valueOf(result.get("status").toString()) == 0
							&& result.get("user_id").toString().length() > 0) {
						_userid = result.get("user_id").toString();
						_phoneNumber = mobileNumber.getText().toString();
						showLoading(getString(Util.getResID("log_sendcode_hint", "string")));
						
						mThread = new Thread(runnable);
						type = 1;
						time.start();
						mThread.start();
					} else {
						Toast.makeText(getApplicationContext(), "用户名错误",
								Toast.LENGTH_SHORT).show();
					}

				} else if (what == 2) {
					showLoading(getString(Util.getResID("getpassword_hint", "string")));
					
					_code = checkCode.getText().toString();
					_phoneNumber = mobileNumber.getText().toString();
					type = 2;
					mThread = new Thread(runnable);
					mThread.start();
				}
			}
		};
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HashMap<String, String> result = HttpUtils
						.HttpGetUserid(_username);
				Message msg = checkhandler.obtainMessage();
				msg.obj = result;
				checkhandler.sendMessage(msg);
			}
		}).start();

		// HashMap<String, String> result = HttpUtils.HttpGetUserid(_username);

	}

	private Boolean checkCode() {
		int un_length = this.checkCode.getText().toString().length();
		int name_length = this.username.getText().toString().length();

		if (un_length <= 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("check_code_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}

		if (name_length <= 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("username_empty_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}
		return true;
	}

	private boolean checkPassword() {
		int pw_length = this.password.getText().toString().length();
		int re_length = this.re_password.getText().toString().length();
		if (pw_length <= 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("password_hint", "string")), Toast.LENGTH_SHORT)
					.show();
			
			return false;
		}
		if (pw_length < 6 || pw_length > 32) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("password_empty_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}
		if (re_length <= 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("confirmpw_empty_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}
		if (re_length < 6 || re_length > 32) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("confirmpw_error_hint1", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}
		if (!this.password.getText().toString()
				.equals(this.re_password.getText().toString())) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("confirmpw_error_hint", "string")),
					Toast.LENGTH_SHORT).show();
			
			return false;
		}
		return true;
	}
	
	private void changePassword(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HashMap<String, String> result = HttpUtils
						.HttpUpdatePasswrd(_username, _password, _code,
								_userid, "2", _phoneNumber);
				Util.LogUtil("forgetPassword---3---result:" + result);
				if (result == null) {
					mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
					return;
				}
				if (result.get("status").equals(
						String.valueOf(REGESTER_SUCCESS))) {
					mHandler.obtainMessage(CHANGE_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
					return;
				}
				status = result.get("status").toString();
				mHandler.obtainMessage(Integer.parseInt(result.get("status")))
						.sendToTarget();
				status = result.get("statis").toString();
			}
		}).start();
		
	
	}

	// ------------------------------------------------------------------------
	// 倒计时处理类
	//
	//
	// ------------------------------------------------------------------------

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_getcode.setText("重新验证");

			// btn_getcode.setBackground(getResources().getDrawable(R.drawable.btn_login_se));
			btn_getcode.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_getcode.setClickable(false);
			// btn_getcode.setBackgroundColor(0xcccccc);
			btn_getcode.setText(millisUntilFinished / 1000 + "秒");
		}
	}
}
